#import "FileDownloader.h"
#import "IDominoAppDelegate.h"

@implementation FileDownloader
- (FileDownloader *)initWithString:(NSString*)url filename:(NSString*)name cookie:(NSString*)cookie
{
	[super init];
	attachmentURL=url;
	filePath=[name retain];
	_sessionCookie=cookie;
	return self;
}

- (void)dealloc
{
	[filePath release];
	[super dealloc];
}


- (void)startDownloadingURL
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	NSURL* url=[NSURL URLWithString:[attachmentURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
	NSMutableURLRequest *downloadRequest=[NSMutableURLRequest requestWithURL:url		  
															cachePolicy:NSURLRequestUseProtocolCachePolicy
														timeoutInterval:60.0];
	[downloadRequest addValue:_sessionCookie forHTTPHeaderField:@"Cookie"];	
	NSURLConnection *downloadConnection=[[NSURLConnection alloc] initWithRequest:downloadRequest delegate:self];	
	if (downloadConnection) {
		receivedData=[[NSMutableData data] retain];
	} else {
	}
	[downloadConnection release];
}

#pragma mark auto called functions
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{	
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];	
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [connection release];	
    [receivedData release];
    NSLog(@"Connection failed! Error - %@ %@",		  
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);	

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
//write this attachment file to local file system	
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	[receivedData writeToFile:filePath atomically:YES];
	
//display this attachment to webView	
	NSURL* url=[NSURL URLWithString:[filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
	NSURLRequest* localLoadingRequest=[[NSURLRequest alloc] initWithURL:url];
	[appDelegate.mailWebView loadRequest:localLoadingRequest];
	[localLoadingRequest release];
	[connection release];	
    [receivedData release];
}

@end
